package com.example.lottery.common.utils;


import io.netty.util.internal.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean set(String key,String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil error,set: {}"+e.getMessage());
            return false;
        }
    }

    public String get(String key) {
        try {
            String str = stringRedisTemplate.opsForValue().get(key);
            return str;
        }catch (Exception e) {
            logger.error("RedisUtil error,get: {}"+e.getMessage());
            return null;
        }
    }

    public boolean set(String key,String value,Long expireTime) {
        try {
            stringRedisTemplate.opsForValue().set(key,value,expireTime, TimeUnit.SECONDS);
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil error,set: {}"+e.getMessage());
            return false;
        }
    }


    public boolean del(String... key) {
        try {
            if (key != null &&  key.length > 0) {
                if (key.length == 1) {
                    stringRedisTemplate.delete(key[0]);
                }else {
                    stringRedisTemplate.delete(
                            (Collection<String>) CollectionUtils.arrayToList(key)
                    );
                }

            }
            return true;
        }catch (Exception e) {
            logger.error("RedisUtil error,del: {}"+e.getMessage());
            return false;
        }
    }


    public boolean hasKey(String key) {
        try {
            return StringUtils.hasText(key) ? stringRedisTemplate.hasKey(key) : false;
        } catch (Exception e) {
            logger.error("RedisUtil error,hasKey: {}"+e.getMessage());
            return false;
        }
    }

}
